#!/usr/bin/env python
# coding: utf-8

# 概念：

# 1.物以类聚，人以群分  2.某处总有和你趣味相投的人  3.趣味相投的人评价来向你推荐

# 对于人来说就是基于用户的过滤，对于物品来说就是基于物品的过滤

# 计算余弦相似度 越接近1越相似，越接近-1越不相似

# from sklearn.metrics.pairwise import cosine_similarity

# sim_AB=cosine_similarity()

# In[2]:


import pandas as pd
import numpy as np


# In[3]:


unames=['user_id','gender','age','occupation','zip']
users=pd.read_table("./movielens/users.dat",sep='::',header=None,names=unames,engine='python')


# In[4]:


users.head()


# In[9]:


rnames=['uesr_id','movie_id','rating','timestamp']
ratings=pd.read_table("./movielens/ratings.dat",sep='::',header=None,names=rnames,engine='python')


# In[10]:


ratings.head()


# In[11]:


mnames=['movie_id','title','genres']
movies=pd.read_table("./movielens/movies.dat",sep='::',header=None,names=mnames,engine='python')


# In[13]:


movies.head()


# In[17]:


data=pd.pivot_table(ratings,index='uesr_id',columns='movie_id',values='rating')


# In[18]:


data.head()


# In[21]:


data.loc[1,1]


# 为uesr_id为1的用户推荐电影

# 第一步：去中心化

# In[22]:


data.info()


# In[25]:


data_center=data.apply(lambda x: x-x.mean(),axis=1)  #去中心化


# In[27]:


from sklearn.metrics.pairwise import cosine_similarity  #引入包


# In[146]:


sim_cos=[]
for i in range(len(data_center)):
    sim_=cosine_similarity(data.iloc[0].fillna(0).values.reshape(1,-1),
                           data.iloc[i].fillna(0).values.reshape(1,-1))
    sim_cos.append(sim_)


# In[147]:


sim_cos


# In[119]:


sim_cos=[x[0][0] for x in sim_cos]


# In[145]:


sim_cos


# In[120]:


data=data.assign(sim=sim_cos)


# In[121]:


data.head()


# In[122]:


data=data.sort_values(by='sim',ascending=False)


# In[123]:


data1=data.iloc[1:6].copy()


# In[124]:


sim1=data1.sim
sim2=pd.DataFrame(data1.sim)
sim2


# In[125]:


data1.dropna(how='all',axis=1,inplace=True)


# In[126]:


data1.sim


# In[127]:


data1


# In[128]:


((~data1.iloc[:,0].isnull()).astype(np.int))*data1.sim


# In[129]:


have_pre=data1[data1.columns[:-1]].apply(lambda x:((x*data1.sim).sum())/(((~x.isnull()).astype(np.int))*data1.sim).sum())


# In[130]:


have_pre[:5]


# In[131]:


len(have_pre)


# In[132]:


have_see=data.columns[~data.iloc[0,:].isnull()][:-1]


# In[133]:


have_see


# In[134]:


pre_movie_id=set(have_pre.index)-set(have_see)


# In[135]:


len(pre_movie_id)


# In[136]:


pre_movie=have_pre[have_pre.index.isin(pre_movie_id)]


# In[137]:


recommend=pre_movie.sort_values(ascending=False)[:10]


# In[138]:


recommend.index


# In[139]:


movies[movies.movie_id.isin(recommend.index)]


# In[140]:


have_see_love=data.sort_values(by=1,axis=1,ascending=False).columns[:10]


# In[141]:


have_see_love


# In[142]:


movies[movies.movie_id.isin(have_see_love)]


# In[ ]:




